
/**
 * Funcion que devuelve una imagen svg de un higchart
 * @author Mauricio Chamorro <mrchamorro@utn.edu.ec>
 * @param {type} charts
 * @returns {String}
 */
Highcharts.getSVG = function(charts) {
    var svgArr = [],
            top = 0,
            width = 0;

    $.each(charts, function(i, chart) {
        var svg = chart.getSVG();
        svg = svg.replace('<svg', '<g transform="translate(0,' + top + ')" ');
        svg = svg.replace('</svg>', '</g>');

        top += chart.chartHeight;
        width = Math.max(width, chart.chartWidth);

        svgArr.push(svg);
    });
    return '<svg height="' + top + '" width="' + width + '" version="1.1" xmlns="http://www.w3.org/2000/svg">' + svgArr.join('') + '</svg>';
};

/**
 * Funcion que permite exportar un array de charts de higchart
 * @author Mauricio Chamorro <mrchamorro@utn.edu.ec>
 * @param {type} charts
 * @param {type} options
 * @returns {undefined}
 */
Highcharts.exportCharts = function(charts, options) {
    var form
    svg = Highcharts.getSVG(charts);

    // merge the options
    options = Highcharts.merge(Highcharts.getOptions().exporting, options);

    // create the form
    form = Highcharts.createElement('form', {
        method: 'post',
        action: options.url
    }, {
        display: 'none'
    }, document.body);

    // add the values
    Highcharts.each(['filename', 'type', 'width', 'svg'], function(name) {
        Highcharts.createElement('input', {
            type: 'hidden',
            name: name,
            value: {
                filename: options.filename || 'chart',
                type: options.type,
                width: options.width,
                svg: svg
            }[name]
        }, null, form);
    });
    //console.log(svg); return;
    // submit
    form.submit();

    // clean up
    form.parentNode.removeChild(form);
};


/**
 * Permite imprimir multiples highcharts
 * @author Mauricio Chamorro <mrchamorro@utn.edu.ec>
 * @param {type} charts
 * @returns {undefined}
 */
function printCharts(charts) {
    var origDisplay = [],
            origParent = [],
            body = document.body,
            childNodes = body.childNodes;
    // hide all body content
    Highcharts.each(childNodes, function(node, i) {
        if (node.nodeType === 1) {
            origDisplay[i] = node.style.display;
            node.style.display = "none";
        }
    });
    // put the charts back in
    $.each(charts, function(i, chart) {
        origParent[i] = chart.container.parentNode;
        body.appendChild(chart.container);
    });
    // print
    window.print();
    // allow the browser to prepare before reverting
    setTimeout(function() {
        // put the chart back in
        $.each(charts, function(i, chart) {
            origParent[i].appendChild(chart.container);
        });

        // restore all body content
        Highcharts.each(childNodes, function(node, i) {
            if (node.nodeType === 1) {
                node.style.display = origDisplay[i];
            }
        });
    }, 500);
}

/**
 * Dibuja una tabla a partir de las series de highchart
 * //TODO:  cambiar medidas 
 * @param {type} identificador
 * @author Mauricio Chamorro <mrchamorro@utn.edu.ec>
 * @returns {undefined}
 */
Highcharts.drawTable = function(identificador) {
//Highcharts.drawTable = function() {//default

    // user options
    var tableTop = 0,
            colWidth = 50,
            tableLeft = 20,
            rowHeight = 20,
            cellPadding = 2,
            valueDecimals = 1,
            valueSuffix = '';

    // internal variables
    var chart = this,
            chart = chart.charts[identificador],
//            chart=chart, //default
            series = chart.series,
            renderer = chart.renderer,
            cellLeft = tableLeft;

    console.log(series);
    console.log("--------");
    // draw category labels
    $.each(chart.xAxis[0].categories, function(i, name) {
        renderer.text(
                name,
                cellLeft + cellPadding,
                tableTop + (i + 2) * rowHeight - cellPadding
                )
                .css({
                    fontWeight: 'bold'
                })
                .add();
    });

    $.each(series, function(i, serie) {
        if (serie._i == 0) {
            cellLeft += colWidth;

            // Apply the cell text
            renderer.text(
                    serie.name,
                    cellLeft - cellPadding + colWidth,
                    tableTop + rowHeight - cellPadding
                    )
                    .attr({
                        align: 'right'
                    })
                    .css({
                        fontWeight: 'bold'
                    })
                    .add();

            $.each(serie.data, function(row, point) {

                // Apply the cell text
                if (Highcharts.numberFormat(point.y, valueDecimals) != 0) {
                    renderer.text(
                            Highcharts.numberFormat(point.y, valueDecimals) + valueSuffix,
                            cellLeft + colWidth - cellPadding,
                            tableTop + (row + 2) * rowHeight - cellPadding
                            )
                            .attr({
                                align: 'right'
                            })
                            .add();

                    // horizontal lines
                    if (row == 0) {
                        Highcharts.tableLine(// top
                                renderer,
                                tableLeft,
                                tableTop + cellPadding,
                                cellLeft + colWidth,
                                tableTop + cellPadding
                                );
                        Highcharts.tableLine(// bottom
                                renderer,
                                tableLeft,
                                tableTop + (serie.data.length + 1) * rowHeight + cellPadding,
                                cellLeft + colWidth,
                                tableTop + (serie.data.length + 1) * rowHeight + cellPadding
                                );
                    }
                    // horizontal line
                    Highcharts.tableLine(
                            renderer,
                            tableLeft,
                            tableTop + row * rowHeight + rowHeight + cellPadding,
                            cellLeft + colWidth,
                            tableTop + row * rowHeight + rowHeight + cellPadding
                            );

                }
            }
            );

            // vertical lines        
            if (i == 0) { // left table border  
                Highcharts.tableLine(
                        renderer,
                        tableLeft,
                        tableTop + cellPadding,
                        tableLeft,
                        tableTop + (serie.data.length + 1) * rowHeight + cellPadding
                        );
            }

            Highcharts.tableLine(
                    renderer,
                    cellLeft,
                    tableTop + cellPadding,
                    cellLeft,
                    tableTop + (serie.data.length + 1) * rowHeight + cellPadding
                    );

            if (i == series.length - 1) { // right table border    

                Highcharts.tableLine(
                        renderer,
                        cellLeft + colWidth,
                        tableTop + cellPadding,
                        cellLeft + colWidth,
                        tableTop + (serie.data.length + 1) * rowHeight + cellPadding
                        );
            }

        }
    });


};

/**
 * Draw a single line in the table
 */
Highcharts.tableLine = function(renderer, x1, y1, x2, y2) {
    renderer.path(['M', x1, y1, 'L', x2, y2])
            .attr({
                'stroke': 'silver',
                'stroke-width': 1
            })
            .add();
}
